package db.day06;

import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;
import org.apache.commons.dbutils.handlers.ColumnListHandler;

import java.sql.SQLException;
import java.util.List;

/**
 * @Author Gan
 * @Date 2021/5/27 19:37
 * @Description:
 */
public class DemoUser {
    public static void main(String[] args) throws SQLException {
        //BeanHandler把ResultSet 封装成单个对象
        queryUserOne();
        System.out.println("==========");
        //查询user集合列
        queryUserList();
        System.out.println("==========");
        //单列
        queryColumnList();

    }

    private static void queryColumnList() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        List<User> col = queryRunner.query("select age from user where username = 'zl'", new ColumnListHandler<User>());
        int affectedRows =
                queryRunner.update("update user set username = '猪八戒' where age = 20 ");
        System.out.println(col);
        System.out.println("affectedRows:" + affectedRows);

    }

    private static void queryUserList() throws SQLException {
        QueryRunner queryRunner = new QueryRunner(DruidUtils.getDataSource());
        List<User> userList =
                queryRunner.query("select username from user where age = 20 ", new BeanListHandler<User>(User.class));
        System.out.println(userList);
    }

    private static void queryUserOne() throws SQLException {
        // 获取QueryRunner对象
        QueryRunner qr = new QueryRunner(DruidUtils.getDataSource());
        /*通过class对象创建 实例对象,
         通过class字节码对象增加一条记录到Bean里
        * */
        User user =
                qr.insert("insert into user values('wu',26,'67269869')", new BeanHandler<>(User.class));
        //System.out.println(user);

    }
}
